package com.study.equ;

import com.study.equ.utils.ModbusCrc16;
import org.junit.jupiter.api.Test;

import java.io.UnsupportedEncodingException;

/**
 * @author zhuzi
 * 2025/1/13 16:27
 */
public class SanBaoDemo {
    private static String orderHead = "55"; // 指令头不参与crc校验 16进制

    private static String orderTail = "AA"; // 指令尾部不参与crc校验 16进制

    private static String order = "1D00000003000000"; // 大屏发送指令

    @Test
    public void sanbao() throws UnsupportedEncodingException {
        String param = "欢迎ABC";
        String instruct_body = encode(param);

        instruct_body = instruct_body.replace(" ", "");
        // 拼接大屏指令

        String instruct = orderHead + ModbusCrc16.getSendData(order + instruct_body) + orderTail;

        instruct = instruct.replace(" ", "");
        System.out.println("示例:" + param);
        System.out.println(instruct);
    }

    public static String encode(String str) throws UnsupportedEncodingException {
        // 根据默认编码获取字节数组
        return encodeEncoding(str, "GBK");
        /*byte[] bytes = str.getBytes("GBK");
        StringBuilder sb = new StringBuilder(bytes.length * 2);
        // 将字节数组中每个字节拆解成2位16进制整数
        for (int i = 0; i < bytes.length; i++) {
            sb.append(hexString.charAt((bytes[i] & 0xf0) >> 4));
            sb.append(hexString.charAt((bytes[i] & 0x0f) >> 0));
            sb.append(" ");
        }
        return sb.toString();*/
    }

    private static String hexString = "0123456789ABCDEF";

    /*
     * 将字符串编码成16进制数字,适用于所有字符（包括中文）
     */
    public static String encodeEncoding(String str, String encoding) throws UnsupportedEncodingException {
        // 根据默认编码获取字节数组
        byte[] bytes = str.getBytes(encoding);
        StringBuilder sb = new StringBuilder(bytes.length * 2);
        // 将字节数组中每个字节拆解成2位16进制整数
        for (int i = 0; i < bytes.length; i++) {
            sb.append(hexString.charAt((bytes[i] & 0xf0) >> 4));
            sb.append(hexString.charAt((bytes[i] & 0x0f) >> 0));
            sb.append(" ");
        }
        return sb.toString();
    }
}
